package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink01_TransForm_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");

        System.out.println("111111111111111111");

        //TODO 3.使用Map将从端口读过来的数据转为WaterSensor
//        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
//            @Override
//            public WaterSensor map(String value) throws Exception {
//                String[] split = value.split(",");
//                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
//            }
//        });
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MyMap());//.setParallelism(2);

        System.out.println("22222222222222222222");

        map.print();

        env.execute();
    }

    public static class MyMap extends RichMapFunction<String,WaterSensor>{

        /**
         * 生命周期方法，最先被调用 每个并行度调用一次 适合用于初始化或者创建链接等操作
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open...");
        }

        /**
         * 生命周期方法，最后被调用 每个并行度调用一次 适合用于清理操作比如关闭链接  只有在读文件的时候会调用两次
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close....");
        }

        @Override
        public WaterSensor map(String value) throws Exception {
            //getRuntimeContext指的是运行时上下文对象，可以获取到更多的信息，比如TaskName，JobId，状态相关的
            System.out.println(getRuntimeContext().getTaskName());
            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        }
    }
}
